<template>
  <NuxtLayout name="userCenter">
    <div class="bg-gray-800 rounded-lg p-6">
      <h2 class="text-2xl font-bold text-white mb-6">我的钱包</h2>

      <!-- 钱包概览 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <!-- 余额 -->
        <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg p-6 text-white">
          <div class="flex items-center justify-between mb-2">
            <span class="text-blue-100">账户余额</span>
            <el-icon :size="24" class="text-blue-200">
              <Wallet />
            </el-icon>
          </div>
          <div class="text-3xl font-bold">￥{{ walletInfo?.balance || '0.00' }}</div>
          <el-button
            type="primary"
            size="small"
            class="mt-4 bg-white text-blue-600 border-white hover:bg-gray-100"
            @click="showRechargeModal = true"
          >
            充值
          </el-button>
        </div>

        <!-- 积分 -->
        <div class="bg-gradient-to-br from-purple-500 to-purple-600 rounded-lg p-6 text-white">
          <div class="flex items-center justify-between mb-2">
            <span class="text-purple-100">我的积分</span>
            <el-icon :size="24" class="text-purple-200">
              <Coin />
            </el-icon>
          </div>
          <div class="text-3xl font-bold">{{ walletInfo?.points || 0 }}</div>
          <p class="text-sm text-purple-100 mt-4">可兑换VIP等权益</p>
        </div>

        <!-- VIP状态 -->
        <div class="bg-gradient-to-br from-yellow-500 to-orange-500 rounded-lg p-6 text-white">
          <div class="flex items-center justify-between mb-2">
            <span class="text-yellow-100">VIP等级</span>
            <el-icon :size="24" class="text-yellow-200">
              <Trophy />
            </el-icon>
          </div>
          <div class="text-3xl font-bold">{{ vipLevelText }}</div>
          <p v-if="walletInfo?.vipExpireTime" class="text-sm text-yellow-100 mt-2">
            {{ daysRemaining }}天后到期
          </p>
          <el-button
            type="warning"
            size="small"
            class="mt-4 bg-white text-orange-600 border-white hover:bg-gray-100"
            @click="showVipModal = true"
          >
            {{ walletInfo?.vipLevel > 0 ? '续费' : '开通' }}
          </el-button>
        </div>
      </div>

      <!-- VIP套餐 -->
      <div class="mb-8">
        <h2 class="text-xl font-semibold text-white mb-4">VIP套餐</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <el-card
            v-for="plan in vipPlans"
            :key="plan.id"
            class="vip-plan-card"
            :body-style="{ padding: '24px' }"
          >
            <div v-if="plan.recommended" class="text-center mb-2">
              <el-tag type="danger" effect="dark">推荐</el-tag>
            </div>
            <h3 class="text-lg font-semibold text-center mb-2 text-white">{{ plan.name }}</h3>
            <div class="text-center mb-4">
              <span class="text-3xl font-bold text-primary">￥{{ plan.price }}</span>
              <span class="text-gray-400">{{ plan.duration }}</span>
            </div>
            <ul class="space-y-2 mb-6">
              <li v-for="feature in plan.features" :key="feature" class="flex items-center text-sm text-gray-300">
                <el-icon class="mr-2 text-green-500">
                  <CircleCheck />
                </el-icon>
                {{ feature }}
              </li>
            </ul>
            <el-button
              :type="plan.recommended ? 'primary' : 'default'"
              class="w-full"
              @click="purchaseVip(plan)"
            >
              立即购买
            </el-button>
          </el-card>
        </div>
      </div>

      <!-- 交易记录 -->
      <div>
        <h2 class="text-xl font-semibold text-white mb-4">交易记录</h2>
        <el-table
          :data="orders"
          style="width: 100%"
          :header-cell-style="{ backgroundColor: '#374151', color: '#fff' }"
          :row-style="{ backgroundColor: '#1f2937' }"
          :cell-style="{ color: '#d1d5db' }"
        >
          <el-table-column prop="orderNo" label="订单号" width="180" />
          <el-table-column prop="productName" label="类型" />
          <el-table-column prop="amount" label="金额">
            <template #default="scope">
              <span class="text-primary">￥{{ scope.row.amount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag
                :type="scope.row.status === 1 ? 'success' : 'info'"
                effect="dark"
              >
                {{ scope.row.status === 1 ? '已支付' : '待支付' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="时间">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
        </el-table>

        <el-empty v-if="!orders || orders.length === 0" description="暂无交易记录" />
      </div>
    </div>

    <!-- 充值弹窗 -->
    <el-dialog v-model="showRechargeModal" title="账户充值" width="500px">
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium mb-2 text-gray-300">充值金额</label>
          <div class="grid grid-cols-3 gap-2">
            <el-button
              v-for="amount in [50, 100, 200, 500, 1000, 2000]"
              :key="amount"
              :type="rechargeAmount === amount ? 'primary' : 'default'"
              @click="rechargeAmount = amount"
            >
              ￥{{ amount }}
            </el-button>
          </div>
          <el-input-number
            v-model="rechargeAmount"
            :min="1"
            :max="10000"
            placeholder="自定义金额"
            class="mt-2 w-full"
          />
        </div>

        <div>
          <label class="block text-sm font-medium mb-2 text-gray-300">支付方式</label>
          <el-radio-group v-model="paymentMethod">
            <el-radio value="alipay">支付宝</el-radio>
            <el-radio value="wechat">微信支付</el-radio>
          </el-radio-group>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end gap-3">
          <el-button @click="showRechargeModal = false">取消</el-button>
          <el-button type="primary" @click="handleRecharge">立即充值</el-button>
        </div>
      </template>
    </el-dialog>
  </NuxtLayout>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { Wallet, Coin, Trophy, CircleCheck } from '@element-plus/icons-vue'

definePageMeta({
  middleware: 'auth'
})

const userStore = useUserStore()

// 状态
const showRechargeModal = ref(false)
const showVipModal = ref(false)
const rechargeAmount = ref(100)
const paymentMethod = ref('alipay')
const walletInfo = ref<any>({})
const orders = ref<any[]>([])

// VIP等级文本
const vipLevelText = computed(() => {
  const level = walletInfo.value?.vipLevel || 0
  const levelMap: Record<number, string> = {
    0: '普通用户',
    1: '黄金VIP',
    2: '铂金VIP',
    3: '钻石VIP'
  }
  return levelMap[level] || '普通用户'
})

// 剩余天数
const daysRemaining = computed(() => {
  if (!walletInfo.value?.vipExpireTime) return 0
  const expire = new Date(walletInfo.value.vipExpireTime).getTime()
  const now = Date.now()
  const days = Math.ceil((expire - now) / (1000 * 60 * 60 * 24))
  return days > 0 ? days : 0
})

// VIP套餐
const vipPlans = [
  {
    id: 1,
    name: '月度VIP',
    price: 19,
    duration: '/月',
    features: ['无广告观看', '高清画质', '优先更新'],
    recommended: false
  },
  {
    id: 2,
    name: '季度VIP',
    price: 49,
    duration: '/3个月',
    features: ['无广告观看', '超清画质', '优先更新', '独家内容'],
    recommended: true
  },
  {
    id: 3,
    name: '年度VIP',
    price: 149,
    duration: '/年',
    features: ['无广告观看', '4K画质', '优先更新', '独家内容', '下载观看'],
    recommended: false
  }
]

// 获取钱包信息
const getWalletInfo = async () => {
  try {
    const data = await $fetch('/dev-api/member/wallet/info', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (data.code === 200) {
      walletInfo.value = data.data || {}
    }
  } catch (error: any) {
    console.error('获取钱包信息失败:', error)
  }
}

// 获取订单列表
const getOrderList = async () => {
  try {
    const data = await $fetch('/dev-api/member/order/list', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      params: {
        pageNum: 1,
        pageSize: 10
      }
    })

    if (data.code === 200) {
      orders.value = data.rows || []
    }
  } catch (error: any) {
    console.error('获取订单列表失败:', error)
  }
}

// 充值
const handleRecharge = async () => {
  if (rechargeAmount.value < 1) {
    ElMessage.warning('请输入正确的充值金额')
    return
  }

  try {
    const data = await $fetch('/dev-api/member/wallet/recharge', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: {
        amount: rechargeAmount.value,
        payMethod: paymentMethod.value
      }
    })

    if (data.code === 200) {
      ElMessage.success(`成功充值 ￥${rechargeAmount.value}`)
      showRechargeModal.value = false
      await getWalletInfo()
      await getOrderList()
    } else {
      ElMessage.error(data.msg || '充值失败')
    }
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '充值失败，请稍后重试')
  }
}

// 购买VIP
const purchaseVip = async (plan: any) => {
  try {
    const data = await $fetch('/dev-api/member/order/create', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: {
        productType: 'vip',
        productId: plan.id,
        amount: plan.price
      }
    })

    if (data.code === 200) {
      // 跳转到支付页面或调用支付接口
      ElMessage.success(`您已成功开通${plan.name}`)
      await getWalletInfo()
      await getOrderList()
    } else {
      ElMessage.error(data.msg || '购买失败')
    }
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '购买失败，请稍后重试')
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

onMounted(() => {
  getWalletInfo()
  getOrderList()
})

// SEO设置
useSeoMeta({
  title: '我的钱包',
  description: '管理您的账户余额和VIP权益',
})
</script>

<style scoped>
.vip-plan-card {
  background-color: rgba(31, 41, 55, 0.8);
  border: 1px solid rgba(55, 65, 81, 0.5);
  transition: all 0.3s;
}

.vip-plan-card:hover {
  border-color: #409EFF;
  transform: translateY(-4px);
}

:deep(.el-dialog) {
  background-color: #1f2937;
  border: 1px solid rgba(55, 65, 81, 0.5);
}

:deep(.el-dialog__title) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-table) {
  background-color: transparent;
}

:deep(.el-table tr) {
  background-color: #1f2937;
}

:deep(.el-table th.el-table__cell) {
  background-color: #374151;
  color: white;
}

:deep(.el-table__empty-block) {
  background-color: #1f2937;
}

:deep(.el-empty__description) {
  color: rgba(255, 255, 255, 0.6);
}
</style>